package com.ccn.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ccn.ui.a3project.A3_1_2FeedAdapter;
import com.squareup.picasso.Picasso;

public class A3Activity extends AppCompatActivity {

    private A3_1_2FeedAdapter mAdapter;
    private RecyclerView recyclerView;

    private View suspensionBar;
    private TextView suspensionNickName;
    private ImageView suspensionAvatar;

    private int mSuspensionHeight;
    private int mCurrentPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_a3_xuanting);

        suspensionBar = findViewById(R.id.suspensionBar);
        suspensionAvatar = findViewById(R.id.iv_avatar);
        suspensionNickName = findViewById(R.id.tv_nickname);

        recyclerView = findViewById(R.id.recyclerView);
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        mAdapter = new A3_1_2FeedAdapter();
        recyclerView.setAdapter(mAdapter);
        recyclerView.setHasFixedSize(true);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //获取悬浮条高度
                mSuspensionHeight = suspensionBar.getHeight();
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //对悬浮条的位置进行调整
                //找到下一个itemview
                View view = manager.findViewByPosition(mCurrentPosition + 1);
                if (view != null) {
                    if (view.getTop() < mSuspensionHeight) {
                        suspensionBar.setY(-(mSuspensionHeight - view.getTop()));
                    } else {
                        suspensionBar.setY(0);
                    }
                }

                if (mCurrentPosition != manager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = manager.findFirstVisibleItemPosition();
                    updateSuspensionBar();
                }
            }
        });
        updateSuspensionBar();
    }

    private void updateSuspensionBar() {
        Picasso.with(this)
                .load(mAdapter.getAvatarResId(mCurrentPosition))
                .centerInside()
                .fit()
                .into(suspensionAvatar);
        suspensionNickName.setText("叮当猫" + mCurrentPosition);
    }
}